package com.jzy.secondhandbooktradingmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.secondhandbooktradingmanagement.entity.Book;
import com.jzy.secondhandbooktradingmanagement.entity.TradeOrder;
import com.jzy.secondhandbooktradingmanagement.entity.TradeOrderDetail;
import com.jzy.secondhandbooktradingmanagement.mapper.BookMapper;
import com.jzy.secondhandbooktradingmanagement.mapper.TradeOrderDetailMapper;
import com.jzy.secondhandbooktradingmanagement.mapper.TradeOrderMapper;
import com.jzy.secondhandbooktradingmanagement.service.ITradeOrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class TradeOrderServiceImpl extends ServiceImpl<TradeOrderMapper, TradeOrder> implements ITradeOrderService {

    @Resource
    private TradeOrderMapper tradeOrderMapper;

    @Resource
    private TradeOrderDetailMapper tradeOrderDetailMapper;

    @Resource
    private BookMapper bookMapper;

    @Override
    @Transactional
    public TradeOrder createOrder(TradeOrder tradeOrder) {
        if (tradeOrder.getDetails() == null || tradeOrder.getDetails().isEmpty()) {
            throw new RuntimeException("订单详情不能为空");
        }

        BigDecimal totalPrice = BigDecimal.ZERO;

        // 1. Validate Inventory and Calculate Total Price
        for (TradeOrderDetail detail : tradeOrder.getDetails()) {
            Book book = bookMapper.selectOne(Wrappers.<Book>lambdaQuery().eq(Book::getIsbn, detail.getIsbn()));
            if (book == null) {
                throw new RuntimeException("图书不存在: " + detail.getIsbn());
            }
            if (book.getInventory() < detail.getQuantity()) {
                throw new RuntimeException("库存不足: " + book.getName());
            }
            
            // Set details info from book
            detail.setBookName(book.getName());
            detail.setPrice(book.getPrice());
            
            // Add to total price
            if (book.getPrice() != null) {
                totalPrice = totalPrice.add(book.getPrice().multiply(BigDecimal.valueOf(detail.getQuantity())));
            }
        }

        // 2. Create Order
        tradeOrder.setOrderNo("ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4));
        tradeOrder.setCreateTime(new Date());
        tradeOrder.setStatus("已创建");
        tradeOrder.setTotalPrice(totalPrice);
        tradeOrderMapper.insert(tradeOrder);

        // 3. Deduct Inventory and Save Details
        for (TradeOrderDetail detail : tradeOrder.getDetails()) {
            Book book = bookMapper.selectOne(Wrappers.<Book>lambdaQuery().eq(Book::getIsbn, detail.getIsbn()));
            
            // Deduct inventory
            book.setInventory(book.getInventory() - detail.getQuantity());
            book.setBorrownum((book.getBorrownum() == null ? 0 : book.getBorrownum()) + detail.getQuantity());
            
            // Check inventory status
            if (book.getInventory() <= 0) {
                book.setStatus("0"); // 下架
            }
            bookMapper.updateById(book);

            // Save detail
            detail.setOrderId(tradeOrder.getId());
            tradeOrderDetailMapper.insert(detail);
        }

        return tradeOrder;
    }

    @Override
    @Transactional
    public void deleteOrder(Integer id) {
        tradeOrderMapper.deleteById(id);
        tradeOrderDetailMapper.delete(Wrappers.<TradeOrderDetail>lambdaQuery().eq(TradeOrderDetail::getOrderId, id));
    }

    @Override
    public Page<TradeOrder> findPage(Integer pageNum, Integer pageSize, String search1, String search2, String search3) {
        LambdaQueryWrapper<TradeOrder> wrappers = Wrappers.<TradeOrder>lambdaQuery();
        if (StringUtils.isNotBlank(search1)) {
            wrappers.like(TradeOrder::getOrderNo, search1);
        }
        if (StringUtils.isNotBlank(search2)) {
            wrappers.eq(TradeOrder::getUserId, search2);
        }
        if (StringUtils.isNotBlank(search3)) {
            wrappers.eq(TradeOrder::getStatus, search3);
        }
        wrappers.orderByDesc(TradeOrder::getCreateTime);
        
        return tradeOrderMapper.selectPage(new Page<>(pageNum, pageSize), wrappers);
    }

    @Override
    public TradeOrder getOrderById(Integer id) {
        TradeOrder tradeOrder = tradeOrderMapper.selectById(id);
        if (tradeOrder != null) {
            List<TradeOrderDetail> details = tradeOrderDetailMapper.selectList(Wrappers.<TradeOrderDetail>lambdaQuery().eq(TradeOrderDetail::getOrderId, id));
            tradeOrder.setDetails(details);
        }
        return tradeOrder;
    }
}
